import Canvas from '../../utils/canvas'
import {
    wxfileTobase64,
    wait
} from '../../utils/util'

Component({
    /**
     * 组件的属性列表
     */
    properties: {
        jobInfo: {
            type: Object
        },
        qrcode: {
            type: String
        }
    },
    created() {            
        
    },
    // 监听他们的变化
    observers: {
        'jobInfo, qrcode': async function (jobInfo, qrcode) {
            if (jobInfo != null && qrcode != '') {
                await wx.loadFontFace({
                    global: true,
                    family: 'PingFangTC-Semibold',
                    source: 'url("https://bullet-static.oss-cn-shanghai.aliyuncs.com/miniprogram/pay/PingFangTC-Semibold.ttf")',
                    scopes: ['webview', 'native'],
                    complete: ()=>{
                        if (typeof jobInfo == 'string') {
                            jobInfo.jobDetail = jobInfo.jobDetail.replace(/[\r\n]/g, '「').split('「')
                        }
                        this.saveQrCode(jobInfo, qrcode)
                    }
                })
            }
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        url: ''
    },

    /**
     * 组件的方法列表
     */
    methods: {
        getImageInfo(src) {
            return new Promise(resolve => {
                wx.getImageInfo({
                    src: src,
                    success: (res => {
                        resolve(res)
                    })
                })
            })
        },

        async saveQrCode(jobInfo, qrcode) {
            const canvasWidth = 287
            const canvasHeight = 429

            const header = '/components/job-share/assets/header.png'
            const headerSrc = await this.getImageInfo(header)
            const headerWidth = headerSrc.width / 2,
                headerHeight = headerSrc.height / 2

            const footer = '/components/job-share/assets/footer.png'
            const footerSrc = await this.getImageInfo(footer)
            const footerWidth = footerSrc.width / 2,
                footerHeight = footerSrc.height / 2

            const company = '/components/job-share/assets/company-icon.png'
            const companySrc = await this.getImageInfo(company)
            const companyWidth = companySrc.width / 2,
                companyHeight = companySrc.height / 2

            // const jobInfo = this.data.jobInfo
            
            wx.showLoading({
                mask: true,
                title: '正在渲染中...',
                complete(res) {
                }
            })
            const ctx = wx.createCanvasContext('myCanvas', this)
            const canvas = new Canvas(ctx)
            canvas.roundRectColor(0, 0, canvasWidth, canvasHeight, 32, '#ffffff')
            // 背景图
            ctx.fillStyle = '#ffffff'
            canvas.circleImage(0, 0, headerWidth, headerHeight, 12, header, [true, true, false, false])
            canvas.circleImage(0, canvasHeight - footerHeight, footerWidth, footerHeight, 12, footer, [false, false, true, true])

            // 内容文本宽度 
            let contentWidth = canvasWidth - 60
            // 岗位招聘标题
            // 先对标题进行分段换行
            ctx.font = 'bold 24px sans-serif \'PingFangTC-Semibold\''
            let chr = jobInfo.jobName
            let temp = ''
            let titleList = []
            const titleLineHeight = 33.5
            for (let a = 0; a < chr.length; a++) {
                if (ctx.measureText(temp).width < contentWidth) {
                    temp += chr[a]
                } else {
                    a-- // 这里添加了a-- 是为了防止字符丢失
                    titleList.push(temp)
                    temp = ''
                }
            }
            await wait(100)
            titleList.push(temp)
            const titleMaxLine = titleList.length < 2 ? titleList.length : 2
            let currentUsedHeight = 73 + (titleLineHeight * titleMaxLine)
            
            // 薪资 lineHeight:29 + marginTop: 11
            ctx.font = '900 29px sans-serif \'PingFangTC-Semibold\''
            canvas.fillText(jobInfo.salary + jobInfo.jobSalaryType, 15, currentUsedHeight + 29 + 11, '#FF7642', 29, 'left', true)
            currentUsedHeight += 29 + 11

            canvas.fillText('扫描二维码，解锁更多好工作', 15, 399 + 12, '#FFFFFF', 11, 'left', false)
            await wait(100)
            // 详情 lineHeight:19 + marginTop: 12.5
            contentWidth = canvasWidth - 40
            currentUsedHeight += 12.5
            ctx.font = '14px sans-serif \'PingFangTC-Semibold\''
            let text = jobInfo.jobAddress
            jobInfo.jobAddress = jobInfo.jobAddress.length > 20 ? jobInfo.jobAddress.substr(0, 20) : jobInfo.jobAddress
            jobInfo.jobAddressTail = text.length > 20 ? text.substr(20, text.length) : ''
            // 地址 y: top + 字号
            canvas.fillText(jobInfo.jobAddress, 58, 324 + 12, '#9497B1', 11, 'left', false)
            canvas.fillText(jobInfo.jobAddressTail, 58, 324 + 24, '#9497B1', 11, 'left', false)
            chr = jobInfo.jobDetail
            temp = ''
            let detailList = []
            // 字行高
            const detailLineHeight = 19
            for (let x = 0; x < chr.length; x++) {
                chr[x] = '·  ' + chr[x]
                for (let a = 0; a < chr[x].length; a++) {
                    if (temp == '' && a > 0) {
                        chr[x] = chr[x].slice(0, a) + '   ' + chr[x].slice(a)
                    }
                    if (ctx.measureText(temp).width < contentWidth) {
                        temp += chr[x][a]
                        if (a == chr[x].length - 1) {
                            detailList.push(temp)
                            temp = ''
                        }
                    } else {
                        a-- // 这里添加了a-- 是为了防止字符丢失
                        detailList.push(temp)
                        temp = ''
                    }
                }
            }

            detailList.push(temp)
            const detailMaxLine = detailList.length < 5 ? detailList.length : 5
            for (let b = 0; b < detailMaxLine; b++) {
                if (b === (detailMaxLine - 1)) detailList[b] = '…'
                canvas.fillText(detailList[b], 15, currentUsedHeight + ((b + 1) * detailLineHeight), '#565868', 14, 'left', false)
            }
            // marginBottom: 17
            currentUsedHeight += 17 + (detailLineHeight * detailMaxLine)
            await wait(100)
            // 标题
            for (let b = 0; b < titleMaxLine; b++) {
                if (b === 1) titleList[b] = titleList[b].substring(0, titleList[b].length - 1) + '…'
                canvas.fillText(titleList[b], 15, 73 + ((b + 1) * titleLineHeight), '#202536', 24, 'left', true)
            }
            // 被派遣单位信息
            // 图标
            canvas.circleImage(15, 305, companyWidth, companyHeight, 12, company, [false, false, false, false])
            // 名称
            canvas.fillText(jobInfo.serveCompanyName, 58, 305 + 13, '#202536', 12, 'left', true)
            // 底部
            // 招聘日期
            const date = jobInfo.createTime.substring(5, 7) + '月' + jobInfo.createTime.substring(8, 10) + '日'
            canvas.fillText(date + '热招岗位', 15, 373 + 21, '#FFFFFF', 21, 'left', true)
            // 二维码
            canvas.fillRect(217, 366, 50, 50, '#ffffff')
            canvas.circleImage(218, 367, 48, 48, 0, qrcode)
            ctx.draw(true)
            ctx.restore()
            await wait(100)
            wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: canvasWidth,
                height: canvasHeight,
                canvasId: 'myCanvas',
                success: (res) => {
                    this.setData({
                        url: res.tempFilePath
                    })
                    wxfileTobase64(res.tempFilePath, true).then(url => {-
                    // console.info(url)
                    // console.log(url,'url')
                    // let arr = []
                    // arr.push({
                    //     path:res.tempFilePath,
                    //     src:url
                    // })
                    wx.hideLoading()
                        // console.log(res,'res')
                        // this.self.setData({
                        //     posterInfo: {
                        //         path: res.tempFilePath,
                        //         src: url
                        //     },  
                        // }, () => {
                        //     // console.log(this.self.data.posterInfo, 'posterInfo')
                        // })
                    })
                },
                fail(err) {
                    console.info(err)
                }
            }, this)
        },
        // 关闭
        onClose() {
            
            this.triggerEvent('close')
        },
        onPreservation() {
            
            this.triggerEvent('preservation', this.data.url)
        }
    },
    
})